package com.yyds.yygh.msm.controller.api;

import com.mysql.jdbc.StringUtils;
import com.yyds.yygh.common.result.Result;
import com.yyds.yygh.msm.service.MsmService;
import com.yyds.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@Api(tags = "短信服务接口")
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("发送手机验证码")
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //检查redis中是否有验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isNullOrEmpty(code)){
            return Result.success();
        }
        //如果redis中获取不到验证码，就生成验证码
        code = RandomUtil.getSixBitRandom();
        //调用service的方法来发送验证码短信
        boolean result = msmService.send(phone, code);
        if (result){
            //把验证码放到redis中，存储2分钟
            redisTemplate.opsForValue().set(phone,code,2,TimeUnit.MINUTES);
            return Result.success();
        }
        return Result.build(509,"发送验证码失败");
    }
}
